<script setup>
import { ref, onMounted, defineProps } from 'vue';
import { getCurrentInstance } from 'vue';
import { ElMessageBox, ElMessage } from 'element-plus';
import { useUserStore } from '../plugins/pinia';

const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const userId = userStore.userInfo.id;

const blog = ref({
  name: '',
  auther: '',
  content: '',
  stars: 3,
  time: '',
  category: '',
  img_url: '',
  view_sum: 0,
});

const props = defineProps({
  blogId: {
    type: [String, Number],
    required: false,
    default: null,
  },
});

// 可用的分类选项
const categories = ref([
  { label: '科技', value: '科技' },
  { label: '旅行', value: '旅行' },
  { label: '生活', value: '生活' },
  { label: '教育', value: '教育' },
  { label: '娱乐', value: '娱乐' },
  { label: '动物', value: '动物' },
  { label: '动漫', value: '动漫' },
  { label: '暂无分类', value: '' },
]);

// 初始化图书数据
onMounted(async () => {
  if (props.blogId) {
    try {
      const response = await proxy.$axios.get(`/book/${props.blogId}`);
      blog.value = response.data.data;
      console.log(blog.value);
    } catch (error) {
      console.error('Error fetching blog details:', error);
    }
  }
});

// 提交图书
const submitBlog = async () => {
  try {
    await proxy.$axios.post('/book', blog.value);
    ElMessage.success('新增图书成功');
    proxy.$emit('navigateTorecommend');
  } catch (error) {
    console.error('Error submitting book:', error);
    ElMessage.error('图书新增失败，请稍后再试');
  }
};

// 取消操作
const cancelEdit = () => {
  ElMessageBox.confirm('确定要取消吗？所有未保存的更改将会丢失。', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      proxy.$emit('navigateTorecommend');
    })
    .catch(() => {
      // 用户取消操作，保持当前状态
    });
};

// 处理图片上传成功
const handleUploadSuccess = (response, file) => {
  blog.value.img_url = response;
  ElMessage.success('图片上传成功');
};
</script>

<template>
  <div class="new-book-container">
    <h2>{{ props.blogId ? '编辑图书信息' : '新增图书' }}</h2>
    <el-form :model="blog" label-width="100px" class="book-form">
      <el-form-item label="标题">
        <el-input v-model="blog.name" placeholder="请输入图书标题" />
      </el-form-item>

      <el-form-item label="作者">
        <el-input v-model="blog.auther" placeholder="请输入作者名称" />
      </el-form-item>

      <el-form-item label="你的评分">
        <el-rate v-model="blog.stars" allow-half />
      </el-form-item>

      <el-form-item label="出版时间">
        <el-date-picker
          v-model="blog.time"
          type="datetime"
          placeholder="请选择出版时间"
          format="YYYY/MM/DD HH:mm:ss"
          style="width: 100%;"
        />
      </el-form-item>

      <el-form-item label="分类">
        <el-select v-model="blog.category" placeholder="请选择图书分类">
          <el-option
            v-for="(item, index) in categories"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="简介">
        <el-input
          type="textarea"
          v-model="blog.content"
          placeholder="请输入图书简介"
          rows="4"
        />
      </el-form-item>

      <el-form-item label="图片">
        <el-upload
          action="http://localhost:8080/upload"
          list-type="picture-card"
          :on-success="handleUploadSuccess"
          :limit="1"
          :on-exceed="() => ElMessage.warning('只能上传一张图片')"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <div v-if="blog.img_url" class="image-preview">
          <img :src="blog.img_url" alt="图书封面" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitBlog">
          {{ props.blogId ? '保存修改' : '新增图书' }}
        </el-button>
        <el-button @click="cancelEdit">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.new-book-container {
  width: 700px;
  margin: 40px auto;
  padding: 20px;
  background: #ffffff;
  border-radius: 12px;
  box-shadow: 0px 4px 12px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  font-weight: bold;
  font-size: 24px;
  color: #333333;
}

.book-form {
  padding: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.image-preview img {
  width: 120px;
  height: 160px;
  border-radius: 8px;
  object-fit: cover;
  margin-top: 10px;
  box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.15);
}

.el-button {
  width: 120px;
}

.el-button + .el-button {
  margin-left: 10px;
}

.el-upload {
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-upload-list {
  margin-top: 10px;
}
</style>

